#include <iostream>
#include <cstring>
#include <utility>

#include "ustring.h"

using namespace std;

inline ustring::ustring()
{
    _str = NULL;
    _len = 0;
}

inline ustring::ustring(const ustring &rhs)
{
    _len = rhs._len;
    if(NULL == rhs._str)
    {
        _str = NULL;
    }
    else
    {
        _str = new char[_len+1];
        strcpy(_str, rhs._str);
    }
}

ustring::ustring(const char *rhs)
{
    if(NULL == rhs)
    {
        _str = NULL;
        _len = 0;
    }
    else
    {
        _len = strlen(rhs);
        _str = new char[_len+1];
        strcpy(_str, rhs);
    }
}

ustring ustring::operator+(const ustring &rhs)
{
    if(NULL != rhs._str)
    {
        ustring s;

        s._len = _len + rhs._len + 1;
        s._str = new char[s._len];

        if(NULL != _str)
        {
            strcpy(s._str, _str);
            strcpy(s._str+strlen(_str), rhs._str);
        }
        else
        {
            strcpy(s._str, _str);
        }

        return s;
    }

    return *this;
}

ustring ustring::operator+(const char *rhs)
{
    if(NULL != rhs)
    {
        ustring s;

        s._len = _len + strlen(rhs) + 1;
        s._str = new char[s._len];

        if(NULL != _str)
        {
            strcpy(s._str, _str);
            strcpy(s._str+strlen(_str), rhs);
        }
        else
        {
            strcpy(s._str, rhs);
        }

        return s;
    }

    return *this;
}

ustring& ustring::operator=(const ustring &rhs)
{
    if(this != &rhs)
    {
        _len = rhs._len;

        delete [] _str;
        _str = NULL;

        if(NULL != rhs._str)
        {
            _str = new char[_len+1];
            strcpy(_str, rhs._str);
        }
    }

    return *this;
}

ustring& ustring::operator=(const char* rhs)
{
    delete [] _str;
    _str = NULL;
    _len = 0;

    if(NULL != rhs)
    {
        _len = strlen(rhs) + 1;
        _str = new char[_len+1];
        strcpy(_str, rhs);
    }

    return *this;
}

//test
//======================================================
void ustring_test(void)
{
    ustring u;
    ustring s("hehe ustring!");
    ustring t = s;

    cout << t.c_str() << endl;

    if(t == s)
    {
        cout << "t == s ustring" << endl;
    }
    else
    {
        cout << "t != u ustring" << endl;
    }

    u = u + "wawa ";
    u = u + t;

    cout << u.c_str() << endl;
}


